<template>
  <div class="class-manage">
    <div class="header">
      <div class="search">
        <span>年级：</span>
        <el-cascader
          v-model="selectedOptions"
          :options="gradeList"
          :props="{
            checkStrictly: true,
            expandTrigger: 'hover',
            value: 'name',
            label: 'name',
          }"
          clearable
          placeholder="请选择年级"
        />
        <el-button class="search-btn" @click="searchClass()">搜索</el-button>
      </div>
      <div class="btns">
        <el-button @click="addClass()">创建班级</el-button>
        <el-button @click="handleDelete()">批量删除</el-button>
      </div>
    </div>
    <!-- 表格 -->
    <div class="chapter-list">
      <el-table
        ref="multipleTableRef"
        :data="classData"
        row-key="id"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column property="name" label="班级名称" width="250" />
        <el-table-column property="id" label="班级编号" width="150" />
        <el-table-column property="grade" label="年级" width="150" />
        <el-table-column property="studentNum" label="学生数量" width="150" />
        <el-table-column label="教学状态" width="200">
          <template #default="scope">
            {{ scope.row.ended ? "结课" : "正在教学中" }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="scope">
            <el-button
              v-if="!scope.row.ended"
              size="small"
              text
              type="primary"
              @click="handleEdit(scope.$index, scope.row)"
              style="color: #457aff; font-size: 14px"
            >
              修改
            </el-button>
            <el-button
              v-if="!scope.row.ended"
              size="small"
              text
              type="primary"
              @click="handleEnd(scope.$index, scope.row)"
              style="color: #457aff; font-size: 14px"
            >
              结课
            </el-button>
            <el-button
              v-if="!scope.row.ended"
              style="margin-left: 0px; color: #457aff; font-size: 14px"
              text
              type="primary"
              size="small"
              @click="handleManage(scope.$index, scope.row)"
            >
              管理学生
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="my_pagination"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        layout="prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 修改班级弹窗 -->
    <el-dialog
      :close-on-click-modal="false"
      v-model="dialogEdit"
      width="650px"
      @close="dialogEdit = false"
      center
    >
      <div class="dialog-body">
        <el-form
          :inline="true"
          :model="form"
          :rules="rules"
          class="demo-form-inline"
        >
          <el-form-item label="班级名称：" prop="calssName">
            <el-input v-model="form.calssName" placeholder="请输入班级名称" />
          </el-form-item>
          <el-form-item label="年级：" prop="grade">
            <el-input-number
              v-model="form.grade"
              :min="2020"
              :max="new Date().getFullYear()"
              controls-position="right"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            style="background-color: #457aff"
            type="primary"
            @click="saveEditClass()"
          >
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import eventBus from "@/utils/eventBus";

export default {
  data() {
    return {
      courseId: "",
      activeName: "first",
      currentPage: 1,
      pageSize: 10,
      total: 0,
      classData: [],
      gradeList: [],
      selectedOptions: [],
      dialogEdit: false,
      classId: "",
      multipleSelection: [],
      form: {
        calssName: "",
        grade: 2020,
      },
      rules: {
        calssName: [
          { required: true, message: "请输入班级名称", trigger: "blur" },
        ],
        grade: [{ required: true, message: "请输入年级", trigger: "blur" }],
      },
    };
  },
  created() {
    this.courseId = JSON.parse(localStorage.getItem("courseId"));
    this.getGradeList();
  },
  methods: {
    // 切换tab
    changeTab(tab) {
      this.activeName = tab;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map((item) => item.id);
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getClassList();
    },

    // 获取班级列表
    getClassList() {
      let classStatus = "";
      let grade = "";

      // 安全地获取选中的值，防止数组为空时报错
      if (this.selectedOptions && this.selectedOptions.length > 0) {
        // 处理第一级选择
        if (this.selectedOptions[0] && this.selectedOptions[0] !== "全部") {
          classStatus = this.selectedOptions[0];
        }

        // 处理第二级选择
        if (
          this.selectedOptions.length > 1 &&
          this.selectedOptions[1] &&
          this.selectedOptions[1] !== "全部"
        ) {
          grade = this.selectedOptions[1];
        }
      }

      this.$axios
        .get(
          `/tes/course/${this.courseId}/class/page?pageNum=${this.currentPage}&pageSize=${this.pageSize}&classStatus=${classStatus}&grade=${grade}`
        )
        .then((res) => {
          if (res.code == "200") {
            this.classData = res.data.content;
            this.total = res.data.total;
          } else {
            this.$message.error(res.message);
          }
        });
    },

    // 获取年级下拉列表
    getGradeList() {
      this.$axios
        .get(
          `/tes/course/${this.courseId}/search/list-class?allFlag=true&defaultClassFlag=false`
        )
        .then((res) => {
          if (res.code == "200") {
            this.gradeList = this.setData(res.data);
            //this.getValue()
            this.$nextTick(() => {
              this.getClassList();
            });
          } else {
            this.$message.error(res.message);
          }
        });
    },
    // 处理数据变成2级
    setData(list) {
      return list.map((item) => {
        const obj = {
          name: item.name,
          defaultedClass: item.defaultedClass,
        };

        if (item.children && item.children.length > 0) {
          obj.children = item.children.map((child) => ({
            name: child.name,
            defaultedClass: child.defaultedClass,
          }));
        }

        return obj;
      });
    },

    // 搜索班级
    searchClass() {
      this.currentPage = 1;
      this.getClassList();
    },
    handleEdit(index, row) {
      this.dialogEdit = true;
      this.form.calssName = row.name;
      this.form.grade = Number(row.grade);
      this.classId = row.id;
      console.log(index, row, 666);
    },

    // 结课
    handleEnd(index, row) {
      this.$confirm("确定要结课吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$axios
          .put(
            `/tes/course/${this.courseId}/class/${row.id}/end-class?errorFlag=true`
          )
          .then((res) => {
            this.getGradeList();
            this.$message.success("结课成功");
            // 结课时通过eventBus通知父组件更新disabledNav状态
            eventBus.emit("updateClassInfo");
          });
      });
    },

    // 管理学生
    handleManage(index, row) {
      this.$router.push({
        path: "/aiTeaching/courseSystem/teachingManage/manageStudent",
        query: {
          classId: row.id,
        },
      });
    },

    // 添加班级
    addClass() {
      this.$router.push({
        path: "/aiTeaching/courseSystem/teachingManage/addClass",
      });
    },

    // 保存修改班级
    saveEditClass() {
      this.$axios
        .put(`/tes/course/${this.courseId}/class/${this.classId}`, {
          grade: this.form.grade,
          name: this.form.calssName,
        })
        .then((res) => {
          if (res.code == "200") {
            this.$message({
              message: "修改成功",
              type: "success",
            });
            this.getGradeList();
            this.dialogEdit = false;
          } else {
            this.$message.error(res.message);
          }
        });
    },

    // 批量删除
    handleDelete() {
      if (this.multipleSelection.length == 0) {
        this.$message({
          message: "请选择要删除的内容",
          type: "warning",
        });
        return;
      }

      this.$confirm("是否删除选中?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: "正在删除中...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });
        this.$axios
          .post(
            `/tes/course/${this.courseId}/class/batch-delete?errorFlag=true`,
            this.multipleSelection
          )
          .then((res) => {
            this.getGradeList();
            this.currentPage = 1;
            this.$message.success("删除成功");
            // 通过eventBus通知父组件更新disabledNav状态
            eventBus.emit("updateClassInfo");
            // 如果当前页没有数据了，回到上一页
            const maxPage = Math.ceil(this.total / this.pageSize);
            if (this.currentPage > maxPage && maxPage > 0) {
              this.currentPage = maxPage;
            }
          })
          .finally(() => {
            loading.close();
          });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.class-manage {
  background-color: #fff;
  padding: 10px 40px 40px 80px;
  box-sizing: border-box;
  min-height: 550px;
  // .tab-btns {
  //   display: flex;
  //   align-items: center;
  //   gap: 10px;
  //   margin-bottom: 30px;
  //   span {
  //     display: flex;
  //     align-items: center;
  //     justify-content: center;
  //     padding: 7px 10px;
  //     font-size: 14px;
  //     color: #457aff;
  //     background: #ffffff;
  //     border-radius: 4px;
  //     border: 1px solid #b2c8ff;
  //     cursor: pointer;
  //     &.active {
  //       background-color: #457aff;
  //       color: #fff;
  //     }
  //   }
  // }
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .search {
      display: flex;
      align-items: center;
      gap: 10px;
      span {
        font-size: 16px;
        color: #252e54;
      }
      .search-btn {
        height: 40px;
        background: #ffffff;
        border-radius: 4px;
        border: 1px solid #a5beff;
        color: #457aff;
        line-height: 40px;
      }
    }
    .btns {
      display: flex;
      align-items: center;
      .el-button {
        background: #457aff;
        border-radius: 4px;
        color: #fff;
      }
    }
  }
  .chapter-list {
    margin-top: 30px;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 20px;
    .my_pagination {
      :deep(.el-pager li.is-active) {
        color: #457aff;
      }
      :deep(.el-pager li:hover) {
        color: #457aff;
      }
    }
  }

  .dialog-body {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 40px 0;
    .el-button {
      color: #457aff;
      border: 1px solid #457aff;
      margin-right: 10px;
      &:hover {
        background-color: #457aff;
        color: #fff;
      }
    }
  }
}
</style>